package com.example.tangyee.activity;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tangyee.R;
import com.example.tangyee.utils.ConstantsUtil;
import com.example.tangyee.utils.ProvinceUtil;
import com.example.tangyee.view.MyCenterPopup;
import com.lxj.xpopup.XPopup;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MaintenanceActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    Unbinder mUnbinder;

    @BindView(R.id.back)
    View back;
    @BindView(R.id.height)
    TextView height;
    @BindView(R.id.weight)
    TextView weight;
    @BindView(R.id.birthday)
    TextView birthday;
    @BindView(R.id.sex)
    RadioGroup sex;
    @BindView(R.id.exercise)
    RadioGroup exercise;
    @BindView(R.id.eat)
    RadioGroup eat;
    @BindView(R.id.isSick)
    RadioGroup isSick;
    @BindView(R.id.isRelativesSick)
    RadioGroup isRelativesSick;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.update)
    TextView update;

    private ProvinceUtil mProvinceUtil;
    StringBuilder stringBuilder = new StringBuilder();
    int level1, level2, level3;

    String value1;
    String value2;
    String value3;
    String value4;
    String value5;
    String value6;
    String value7;
    String value8;
    String value9;

    private HandlerThread mThread = new HandlerThread("maintenance");
    private Handler mWorkHandler = new Handler(mThread.getLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    updateInfo();
                    break;
            }
        }
    };

    private void updateInfo() {
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody body = new FormBody.Builder()
                .add("height", value1)
                .add("weight", value2)
                .add("birthday", value3)
                .add("sex", value4)
                .add("isSport", value5)
                .add("isGourmand", value6)
                .add("hasDiabetes", value7)
                .add("hasFamilyDiabetes", value8)
                .add("province", mProvinceUtil.provinceBeanList.get(level1).getName())
                .add("city", mProvinceUtil.cityList.get(level1).get(level2))
                .add("district", mProvinceUtil.districtList.get(level1).get(level2).get(level3))
                .build();

        Request request = new Request.Builder()
                .url(ConstantsUtil.UPDATE_INFO)
                .post(body)
                .build();

        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                runOnUiThread(() -> {
                    XPopup.get(MaintenanceActivity.this).dismiss("loading");
                    Toast.makeText(MaintenanceActivity.this, "更新成功！", Toast.LENGTH_SHORT).show();
                });
            } else {
                runOnUiThread(() -> {
                    XPopup.get(MaintenanceActivity.this).dismiss("loading");
                    Toast.makeText(MaintenanceActivity.this, "更新失败！", Toast.LENGTH_SHORT).show();
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintenance);
        mProvinceUtil = new ProvinceUtil(this);
        mUnbinder = ButterKnife.bind(this);

        sex.setOnCheckedChangeListener(this);
        exercise.setOnCheckedChangeListener(this);
        isSick.setOnCheckedChangeListener(this);
        isRelativesSick.setOnCheckedChangeListener(this);
        eat.setOnCheckedChangeListener(this);
    }


    @OnClick({R.id.height, R.id.weight, R.id.birthday, R.id.address, R.id.update, R.id.back})
    void dealClickedEvent(View view) {
        switch (view.getId()) {
            case R.id.height:
                String[] items1 = new String[191];
                for (int i = 60; i <= 250; i ++) {
                    items1[i - 60] = i + "";
                }
                XPopup.get(MaintenanceActivity.this).asCustom(new MyCenterPopup(MaintenanceActivity.this, items1, new MyCenterPopup.PopupHelper(){
                    @Override
                    public String getTitle() {
                        return "身高";
                    }

                    @Override
                    public void onSelect(View view, int position) {
                        height.setText(items1[position]);
                        value1 = items1[position];
                    }
                }, 110)).show();
                break;
            case R.id.weight:
                String[] items2 = new String[221];
                for (int i = 30; i <= 250; i ++) {
                    items2[i - 30] = i + "";
                }
                XPopup.get(MaintenanceActivity.this).asCustom(new MyCenterPopup(MaintenanceActivity.this, items2, new MyCenterPopup.PopupHelper(){
                    @Override
                    public String getTitle() {
                        return "身高";
                    }

                    @Override
                    public void onSelect(View view, int position) {
                        weight.setText(items2[position]);
                        value2 = items2[position];
                    }
                }, 30)).show();
                break;
            case R.id.birthday:
                Calendar calendar = Calendar.getInstance();
                DatePickerDialog datePickerDialog = new DatePickerDialog(MaintenanceActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        Date d = new GregorianCalendar(year, month, dayOfMonth, 0, 0, 0).getTime();
                        if (new Date().getTime() >= d.getTime()) {
                            String recordDate = year + "/" + (month+1) + "/" + dayOfMonth;
                            birthday.setText(recordDate);
                            value3 = recordDate;
                        }
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
                datePickerDialog.show();
                break;
            case R.id.address:
                stringBuilder = new StringBuilder();
                String[] items3 = new String[mProvinceUtil.provinceBeanList.size()];
                for (int i = 0; i < mProvinceUtil.provinceBeanList.size(); i ++) {
                    items3[i] = mProvinceUtil.provinceBeanList.get(i).getName();
                }
                XPopup.get(MaintenanceActivity.this).asCustom(new MyCenterPopup(MaintenanceActivity.this, items3, new MyCenterPopup.PopupHelper(){
                    @Override
                    public String getTitle() {
                        return "选择省份";
                    }

                    @Override
                    public void onSelect(View view, int position) {
                        level1 = position;
                        stringBuilder.append(items3[position] + ",");
                        String province = items3[position];
                        List<String> cityList = mProvinceUtil.cityList.get(position);
                        String[] citys = new String[cityList.size()];
                        cityList.toArray(citys);
                        XPopup.get(MaintenanceActivity.this).asCustom(new MyCenterPopup(MaintenanceActivity.this, citys, new MyCenterPopup.PopupHelper(){
                            @Override
                            public String getTitle() {
                                return province;
                            }

                            @Override
                            public void onSelect(View view, int position) {
                                level2 = position;
                                stringBuilder.append(citys[position] + ",");
                                List<String> districtList = mProvinceUtil.districtList.get(level1).get(level2);
                                String[] districts = new String[districtList.size()];
                                districtList.toArray(districts);
                                XPopup.get(MaintenanceActivity.this).asCustom(new MyCenterPopup(MaintenanceActivity.this, districts, new MyCenterPopup.PopupHelper(){
                                    @Override
                                    public String getTitle() {
                                        return province;
                                    }

                                    @Override
                                    public void onSelect(View view, int position) {
                                        level3 = position;
                                        stringBuilder.append(districts[position]);
                                        address.setText(stringBuilder.toString());
                                        value9 = stringBuilder.toString();
                                    }
                                })).show();
                            }
                        })).show();
                    }
                })).show();
                break;
            case R.id.update:
                if (value1 == null) {
                    Toast.makeText(this, "身高未填写",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (value2 == null) {
                    Toast.makeText(this, "体重未填写",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (value3 == null) {
                    Toast.makeText(this, "生日未填写",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (value4 == null) {
                    Toast.makeText(this, "性别未填写",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (value5 == null) {
                    Toast.makeText(this, "是否常运动未填写",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (value6 == null) {
                    Toast.makeText(this, "是否大吃大喝未填写",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (value7 == null) {
                    Toast.makeText(this, "是否患有糖尿病未填写",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (value8 == null) {
                    Toast.makeText(this, "亲属是否患有糖尿病未填写",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (value9 == null) {
                    Toast.makeText(this, "籍贯未填写",Toast.LENGTH_SHORT).show();
                    return;
                }
                Message message = mWorkHandler.obtainMessage();
                message.what = 1;
                mWorkHandler.sendMessage(message);
                XPopup.get(this).asLoading().show("loading");
                break;
            case R.id.back:
                onBackPressed();
                break;
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (group.getId()) {
            case R.id.sex:
                value4 = ((RadioButton) findViewById(checkedId)).getText().toString();
                break;
            case R.id.exercise:
                value5 = ((RadioButton) findViewById(checkedId)).getText().toString();
                break;
            case R.id.eat:
                value6 = ((RadioButton) findViewById(checkedId)).getText().toString();
                break;
            case R.id.isSick:
                value7 = ((RadioButton) findViewById(checkedId)).getText().toString();
                break;
            case R.id.isRelativesSick:
                value8 = ((RadioButton) findViewById(checkedId)).getText().toString();
                break;
        }
    }
}
